<template>
  <Head title="购物车" />
  <ShopLayout>
    <!-- Shopping Cart - Orange Tech Style -->
    <div class="bg-gray-100 min-h-screen">
      <div class="max-w-7xl mx-auto px-8 sm:px-16 lg:px-24 py-20">
        <!-- Page Title and Batch Actions -->
        <div class="flex items-center justify-between mb-8">
          <h1 class="text-3xl font-light text-gray-900">购物车</h1>
          
          <!-- Batch Actions (only show when items exist) -->
          <div v-if="cartItems.length > 0" class="flex items-center gap-4">
            <button
              @click="selectAll"
              class="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors"
            >
              {{ selectedItems.length === validItems.length ? '取消全选' : '全选' }}
            </button>
            <button
              v-if="selectedItems.length > 0"
              @click="confirmBatchRemove"
              class="text-sm font-medium text-red-600 hover:text-red-700 transition-colors"
            >
              删除选中 ({{ selectedItems.length }})
            </button>
            <button
              v-if="invalidItems.length > 0"
              @click="confirmClearInvalid"
              class="text-sm font-medium text-amber-600 hover:text-amber-700 transition-colors"
            >
              清理失效商品 ({{ invalidItems.length }})
            </button>
            <button
              v-if="cartItems.length > 0"
              @click="confirmClearCart"
              class="text-sm font-medium text-gray-600 hover:text-gray-700 transition-colors"
            >
              清空购物车
            </button>
          </div>
        </div>
        
        <!-- Invalid Items Alert -->
        <div v-if="invalidItems.length > 0" class="mb-6 bg-amber-50 border border-amber-200 rounded-2xl p-6">
          <div class="flex items-start gap-4">
            <div class="flex-shrink-0">
              <svg class="w-6 h-6 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
              </svg>
            </div>
            <div class="flex-1">
              <h3 class="text-sm font-medium text-amber-900 mb-1">购物车中有 {{ invalidItems.length }} 件商品失效</h3>
              <p class="text-sm text-amber-700">失效商品无法结算，建议清理后再继续购物。</p>
            </div>
            <button
              @click="confirmClearInvalid"
              class="flex-shrink-0 px-4 py-2 text-sm font-medium text-amber-700 bg-white border border-amber-300 rounded-xl hover:bg-amber-50 transition-colors"
            >
              立即清理
            </button>
          </div>
        </div>
        
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <!-- Cart Items -->
          <div :class="cartItems.length === 0 ? 'lg:col-span-3' : 'lg:col-span-2'">

            <!-- Empty Cart -->
            <div v-if="cartItems.length === 0" class="bg-white rounded-2xl p-8 text-center py-20">
              <div class="w-24 h-24 bg-gray-200 rounded-full flex items-center justify-center mx-auto mb-6">
                <svg class="w-12 h-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l-1 7a2 2 0 01-2 2H8a2 2 0 01-2-2L5 9z" />
                </svg>
              </div>
              <h3 class="text-xl font-medium text-gray-900 mb-2">购物车为空</h3>
              <p class="text-gray-600 mb-8">开始购物，添加一些商品到购物车吧！</p>
              <Link href="/" class="inline-flex items-center px-6 py-3 bg-gray-900 text-white rounded-2xl font-medium hover:bg-gray-800 transition-colors">
                继续购物
              </Link>
            </div>

            <!-- Cart Items List -->
            <div v-else class="space-y-6">
              <div 
                v-for="item in cartItems" 
                :key="item.id" 
                :class="[
                  'bg-white rounded-2xl p-6 shadow-sm',
                  item.is_invalid && 'opacity-60 relative'
                ]"
              >
                <!-- Invalid Badge -->
                <div v-if="item.is_invalid" class="absolute top-4 right-4 px-3 py-1 bg-amber-100 text-amber-800 text-xs font-medium rounded-full">
                  {{ item.invalid_reason }}
                </div>
                
                <div class="flex items-start gap-6">
                  <!-- Checkbox -->
                  <div class="flex-shrink-0 pt-2">
                    <input
                      type="checkbox"
                      :checked="item.is_selected"
                      @change="toggleItem(item.id)"
                      :disabled="item.is_invalid"
                      :class="[
                        'w-5 h-5 text-gray-900 border-gray-300 rounded focus:ring-gray-900',
                        item.is_invalid ? 'cursor-not-allowed' : 'cursor-pointer'
                      ]"
                    />
                  </div>
                  
                  <!-- Product Image -->
                  <div class="flex-shrink-0">
                    <div class="w-24 h-24 bg-gray-50 rounded-xl overflow-hidden">
                      <img :src="item.image" :alt="item.name" class="w-full h-full object-contain" />
                    </div>
                  </div>

                  <!-- Product Info -->
                  <div class="flex-1 min-w-0">
                    <div class="flex justify-between items-start">
                      <div>
                        <h3 class="text-lg font-medium text-gray-900 mb-1">{{ item.name }}</h3>
                        <p class="text-gray-600 text-sm mb-2">{{ item.description }}</p>
                        
                        <!-- Product Specs -->
                        <div v-if="item.specs && item.specs.length > 0" class="flex flex-wrap gap-2 mb-3">
                          <span v-for="(spec, index) in item.specs" :key="index" class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-700">
                            {{ spec.name }}: {{ spec.value }}
                          </span>
                        </div>
                      </div>
                      
                      <!-- Price -->
                      <div class="text-right">
                        <p class="text-xl font-medium text-gray-900">¥{{ (item.price * item.quantity).toLocaleString() }}</p>
                        <p v-if="item.originalPrice" class="text-sm text-gray-500 line-through">¥{{ (item.originalPrice * item.quantity).toLocaleString() }}</p>
                      </div>
                    </div>

                    <!-- Quantity Controls -->
                    <div class="flex items-center justify-between mt-4">
                      <div class="flex items-center gap-4">
                        <span class="text-sm text-gray-600">数量:</span>
                        <div class="flex items-center gap-2">
                          <button
                            @click="updateQuantity(item.id, item.quantity - 1)"
                            :disabled="item.quantity <= 1"
                            class="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                          >
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 12H4" />
                            </svg>
                          </button>
                          <span class="w-8 text-center font-medium">{{ item.quantity }}</span>
                          <button
                            @click="updateQuantity(item.id, item.quantity + 1)"
                            :disabled="item.quantity >= item.stock"
                            class="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                          >
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                            </svg>
                          </button>
                        </div>
                        <span class="text-sm text-gray-500">库存: {{ item.stock }}</span>
                      </div>

                      <!-- Remove Button -->
                      <button
                        @click="confirmRemove(item)"
                        class="text-sm font-medium text-red-600 hover:text-red-700 transition-colors"
                      >
                        删除
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Order Summary -->
          <div v-if="cartItems.length > 0" class="lg:col-span-1">
            <div class="bg-white rounded-2xl p-6 shadow-sm sticky top-8">
              <div class="flex items-center justify-between mb-6">
                <h2 class="text-xl font-medium text-gray-900">订单摘要</h2>
                <span v-if="selectedItems.length > 0 && selectedItems.length < cartItems.length" class="text-sm text-gray-500">
                  已选 {{ selectedItemCount }} 件
                </span>
              </div>

              <!-- Summary Details -->
              <div class="space-y-4 mb-6">
                <!-- 商品明细 -->
                <div class="space-y-3 pb-4 border-b border-gray-200">
                  <div v-for="item in selectedItems" :key="item.id" class="flex justify-between text-sm">
                    <div class="flex-1">
                      <p class="text-gray-900 font-medium">{{ item.name }}</p>
                      <p class="text-gray-500 text-xs mt-0.5">
                        <span v-if="item.specs && item.specs.length > 0">
                          {{ item.specs.map(s => s.value).join(' / ') }}
                        </span>
                        <span class="ml-2">× {{ item.quantity }}</span>
                      </p>
                    </div>
                    <span class="text-gray-900 ml-4">¥{{ (item.price * item.quantity).toLocaleString() }}</span>
                  </div>
                </div>
                
                <div class="flex justify-between text-sm">
                  <span class="text-gray-600">商品小计</span>
                  <span class="text-gray-900">¥{{ subtotal.toLocaleString() }}</span>
                </div>
                
                <div class="flex justify-between text-sm">
                  <span class="text-gray-600">运费</span>
                  <span class="text-gray-900">{{ shipping === 0 ? '免费' : `¥${shipping.toLocaleString()}` }}</span>
                </div>
                
                <div v-if="discount > 0" class="flex justify-between text-sm">
                  <span class="text-gray-600">优惠券</span>
                  <span class="text-green-600">-¥{{ discount.toLocaleString() }}</span>
                </div>
                
                <div class="border-t border-gray-200 pt-4">
                  <div class="flex justify-between text-lg font-medium">
                    <span class="text-gray-900">总计</span>
                    <span class="text-gray-900">¥{{ total.toLocaleString() }}</span>
                  </div>
                </div>
              </div>

              <!-- Checkout Button -->
              <button
                @click="checkout"
                :disabled="cartItems.length === 0 || selectedItems.length === 0"
                class="w-full bg-gray-900 text-white py-4 px-6 rounded-2xl font-medium hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors mb-4"
              >
                {{ selectedItems.length === 0 ? '请选择商品' : `去结算 (${selectedItemCount} 件)` }}
              </button>

              <!-- Continue Shopping -->
              <Link href="/" class="block w-full text-center text-gray-600 hover:text-gray-800 py-2 transition-colors">
                继续购物
              </Link>

              <!-- Orange Tech Services -->
              <div class="mt-8 pt-6 border-t border-gray-200">
                <h3 class="text-sm font-medium text-gray-900 mb-4">Orange Tech 服务</h3>
                <div class="space-y-3">
                  <div class="flex items-center text-sm text-gray-600">
                    <svg class="w-4 h-4 text-green-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                    </svg>
                    免费送货
                  </div>
                  <div class="flex items-center text-sm text-gray-600">
                    <svg class="w-4 h-4 text-green-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                    </svg>
                    Orange Tech 支持
                  </div>
                  <div class="flex items-center text-sm text-gray-600">
                    <svg class="w-4 h-4 text-green-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                    </svg>
                    以旧换新
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <ConfirmDialog
      :show="showRemoveDialog"
      type="danger"
      title="确认删除商品"
      :message="removeDialogMessage"
      confirm-text="删除"
      cancel-text="取消"
      @close="showRemoveDialog = false"
      @confirm="confirmRemoveItem"
    />
  </ShopLayout>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Head, Link, router } from '@inertiajs/vue3'
import ShopLayout from '@/Layouts/ShopLayout.vue'
import ConfirmDialog from '@/Components/ConfirmDialog.vue'
import { useNotification } from '@/composables/useNotification'

// 接收服务端购物车数据
const props = defineProps({
  cartItems: {
    type: Array,
    default: () => []
  },
  summary: {
    type: Object,
    default: () => ({
      subtotal: 0,
      shipping: 0,
      discount: 0,
      total: 0,
      itemCount: 0
    })
  }
})

const cartItems = computed(() => props.cartItems || [])

// 通知功能
const { showSuccess, showError } = useNotification()

// 选中状态由后端管理，不需要前端状态

// 删除确认对话框
const showRemoveDialog = ref(false)
const itemToRemove = ref(null)
const batchRemoveType = ref(null) // 'batch' or 'clear'

// 删除对话框消息
const removeDialogMessage = computed(() => {
  if (!itemToRemove.value) return ''
  
  let message = `确定要将 "${itemToRemove.value.name}" 从购物车中移除吗？`
  
  if (itemToRemove.value.specs && itemToRemove.value.specs.length > 0) {
    const specs = itemToRemove.value.specs.map(s => `${s.name}: ${s.value}`).join(', ')
    message += `\n\n规格：${specs}`
  }
  
  return message
})

// 使用后端计算的汇总数据
const subtotal = computed(() => props.summary.subtotal)
const shipping = computed(() => props.summary.shipping)
const discount = computed(() => props.summary.discount)
const total = computed(() => props.summary.total)
const selectedItemCount = computed(() => props.summary.selectedItemCount)

// 计算选中商品数量（用于UI显示）
const selectedItems = computed(() => {
  return cartItems.value.filter(item => item.is_selected)
})

// 计算失效商品数量
const invalidItems = computed(() => {
  return cartItems.value.filter(item => item.is_invalid)
})

// 计算有效商品数量
const validItems = computed(() => {
  return cartItems.value.filter(item => !item.is_invalid)
})

// 方法
const updateQuantity = (itemId, newQuantity) => {
  if (newQuantity <= 0) return
  router.post(route('cart.update'), { item_id: itemId, quantity: newQuantity }, { 
    preserveScroll: true,
    preserveState: false, // 允许重新加载页面状态和全局共享数据
    onSuccess: () => {
      showSuccess('数量已更新', '')
    },
    onError: () => {
      showError('更新失败', '请重试')
    }
  })
}

const confirmRemove = (item) => {
  itemToRemove.value = item
  batchRemoveType.value = null
  showRemoveDialog.value = true
}

const checkout = () => {
  if (cartItems.value.length === 0) {
    showError('购物车为空', '')
    return
  }
  
  if (selectedItems.value.length === 0) {
    showError('请选择要结算的商品', '')
    return
  }
  
  router.visit(route('checkout') + '?from=cart')
}

// 批量操作方法 - 调用后端API
const toggleItem = (itemId) => {
  router.post(route('cart.toggle-select'), { item_id: itemId }, {
    preserveScroll: true,
    preserveState: false,
  })
}

const selectAll = () => {
  // 只对有效商品进行全选/取消全选操作
  const allValidSelected = selectedItems.value.length === validItems.value.length
  router.post(route('cart.toggle-select-all'), { selected: !allValidSelected }, {
    preserveScroll: true,
    preserveState: false,
  })
}

const confirmBatchRemove = () => {
  if (selectedItems.value.length === 0) {
    showError('请先选择要删除的商品', '')
    return
  }
  
  batchRemoveType.value = 'batch'
  itemToRemove.value = { 
    name: `${selectedItems.value.length} 件商品`,
    specs: null
  }
  showRemoveDialog.value = true
}

// 获取选中商品的ID列表
const selectedItemIds = computed(() => {
  return selectedItems.value.map(item => item.id)
})

const confirmClearCart = () => {
  batchRemoveType.value = 'clear'
  itemToRemove.value = { 
    name: '购物车中的所有商品',
    specs: null
  }
  showRemoveDialog.value = true
}

const confirmClearInvalid = () => {
  batchRemoveType.value = 'clear-invalid'
  itemToRemove.value = { 
    name: `${invalidItems.value.length} 件失效商品`,
    specs: null
  }
  showRemoveDialog.value = true
}

const confirmRemoveItem = () => {
  if (!itemToRemove.value) return
  
  // 批量删除
  if (batchRemoveType.value === 'batch') {
    router.post(route('cart.batch-remove'), { item_ids: selectedItemIds.value }, { 
      preserveScroll: true,
      preserveState: false,
      onSuccess: () => {
        showRemoveDialog.value = false
        itemToRemove.value = null
        batchRemoveType.value = null
      },
      onError: () => {
        showError('删除失败', '请重试')
      }
    })
  } 
  // 清空购物车
  else if (batchRemoveType.value === 'clear') {
    router.post(route('cart.clear'), {}, { 
      preserveScroll: true,
      preserveState: false,
      onSuccess: () => {
        showRemoveDialog.value = false
        itemToRemove.value = null
        batchRemoveType.value = null
      },
      onError: () => {
        showError('清空失败', '请重试')
      }
    })
  }
  // 清理失效商品
  else if (batchRemoveType.value === 'clear-invalid') {
    router.post(route('cart.clear-invalid'), {}, { 
      preserveScroll: true,
      preserveState: false,
      onSuccess: () => {
        showRemoveDialog.value = false
        itemToRemove.value = null
        batchRemoveType.value = null
      },
      onError: () => {
        showError('清理失败', '请重试')
      }
    })
  }
  // 单个删除
  else {
    router.post(route('cart.remove'), { item_id: itemToRemove.value.id }, { 
      preserveScroll: true,
      preserveState: false,
      onSuccess: () => {
        showRemoveDialog.value = false
        itemToRemove.value = null
      },
      onError: () => {
        showError('移除失败', '请重试')
      }
    })
  }
}
</script>